#!/usr/bin/env python3
"""
Configuration file loader - Supports loading different model configurations from command line
"""

import os
import sys
import importlib.util

class ConfigLoader:
    """Configuration file loader"""
    
    @staticmethod
    def load_config(config_path):
        """
        Load configuration file from specified path
        
        Args:
            config_path (str): Configuration file path, can be absolute or relative path
            
        Returns:
            object: Configuration class instance
        """
        # Ensure path is absolute
        if not os.path.isabs(config_path):
            config_path = os.path.abspath(config_path)
        
        # Check if file exists
        if not os.path.exists(config_path):
            raise FileNotFoundError(f"Configuration file does not exist: {config_path}")
        
        # Dynamically import configuration file
        spec = importlib.util.spec_from_file_location("config_module", config_path)
        config_module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(config_module)
        
        # Find configuration classes (classes that are configuration classes)
        config_classes = []
        for attr_name in dir(config_module):
            attr = getattr(config_module, attr_name)
            if isinstance(attr, type):
                # Check if it's a model configuration class (contains MODEL_NAME attribute)
                if hasattr(attr, 'MODEL_NAME'):
                    config_classes.append((attr_name, attr))
                # Also include classes ending with 'Config' as fallback
                elif attr_name.endswith('Config'):
                    config_classes.append((attr_name, attr))
        
        if not config_classes:
            raise ValueError(f"No configuration class found in configuration file {config_path}")
        
        # Prefer model configuration classes (those with MODEL_NAME attribute)
        model_configs = [cls for name, cls in config_classes if hasattr(cls, 'MODEL_NAME')]
        
        if model_configs:
            # Use the first model configuration class
            config_class = model_configs[0]
        else:
            # Fall back to the first found configuration class
            config_class = config_classes[0][1]
        
        return config_class()
    
    @staticmethod
    def list_available_configs():
        """List all available configuration files"""
        config_dir = os.path.join(os.path.dirname(__file__), 'config')
        config_files = []
        
        if os.path.exists(config_dir):
            for file in os.listdir(config_dir):
                if file.endswith('.py') and not file.startswith('__'):
                    config_files.append(file)
        
        return sorted(config_files)
    
    @staticmethod
    def get_config_path(config_name):
        """
        Get configuration file path based on configuration name
        
        Args:
            config_name (str): Configuration name (e.g., 'unet', 'segformer')
            
        Returns:
            str: Configuration file path
        """
        # Handle different input formats
        if config_name.endswith('.py'):
            filename = config_name
        else:
            filename = f"{config_name}.py"
        
        config_path = os.path.join(os.path.dirname(__file__), 'config', filename)
        
        if not os.path.exists(config_path):
            # Try adding .py extension
            if not config_path.endswith('.py'):
                config_path += '.py'
        
        return config_path


def main():
    """Test configuration loader"""
    loader = ConfigLoader()
    
    print("Available configuration files:")
    config_files = loader.list_available_configs()
    for file in config_files:
        print(f"  - {file}")
    
    # Test loading a configuration
    if config_files:
        test_config = config_files[0]
        config_path = loader.get_config_path(test_config.replace('_config.py', ''))
        
        try:
            config = loader.load_config(config_path)
            print(f"\nSuccessfully loaded configuration: {test_config}")
            print(f"Model name: {config.MODEL_NAME}")
            print(f"Encoder: {config.ENCODER_NAME}")
        except Exception as e:
            print(f"Failed to load configuration: {e}")

if __name__ == "__main__":
    main()